from django.http import JsonResponse
from rest_framework_jwt.utils import jwt_decode_handler
from opwf.settings import AUTH_WHITE_LIST
from users.models import User


def simple_middleware_token(get_response):
    # get_response  是处理request的函数,  中间件修改request,  并不处理request=>response
    # 此处编写的代码仅在Django第一次配置和初始化的时候执行一次。
    def middleware(request):
        if request.method == 'POST' and request.path == '/login/':
            response = get_response(request)
            return response
        # 1. 处理token
        # 1. 根本没有执行到这一行,
        # 2. 你有多个进程, python.exe,  全杀掉,
        else:
            jwt_value = request.META['HTTP_AUTHORIZATION'].split(' ')[1]  # 'JWT XXXX'

            data = jwt_decode_handler(jwt_value)
            user_id = data.get('user_id')
            user = User.objects.get(id=user_id)
            request.user = user

            response = get_response(request)
            return response

    return middleware


def simple_middleware(get_response):
    # get_response  是处理request的函数,  中间件修改request,  并不处理request=>response
    # 此处编写的代码仅在Django第一次配置和初始化的时候执行一次。
    print('1.初始化中间件')

    def middleware(request):
        # 1. 记录每个url的浏览量,
        # 2. 限流
        # 3. 认证
        # 4. rbac 权限, url, user, 根据用户判断一下, 有没有访问这个url的权限
        # 5. ip黑名单, 反爬虫, request, user-agent
        # 此处编写的代码会在每个请求处理视图前被调用。

        path = request.path
        method = request.method
        user = request.user

        if user.is_superuser:
            response = get_response(request)
            return response

        if path in AUTH_WHITE_LIST:
            response = get_response(request)
            return response

        # 拥有的权限列表
        auth_list = []  # ['get_/user/', 'post_/user/', 'put_/user/']

        for auth in user.role.authorization.all():
            s = '%s_%s' % (auth.motheds, auth.url)
            auth_list.append(s)

        # 需要的权限
        now_auth = '%s_%s' % (method.lower(), path)  # 'get_/user/',   'get_/'
        flag = False
        for auth in auth_list:
            if now_auth.startswith(auth):
                flag = True
        if flag:
            response = get_response(request)
            return response
        else:
            return JsonResponse({'msg': '没有权限'})

    return middleware